/**
 * @file writer.c
 * Betriebssysteme Shared Memory Writer.
 *
 * Beispiel 2
 *
 * @author Markus Scharitzer 1410258040 <markus.scharitzer@technikum-wien.at>
 * @author Helene Wiesinger 1410258004 <helene.wiesinger@technikum-wien.at>
 * @author Siegfried Becher 141025035 <siegfried.becher@technikum-wien.at>
 * @date 2015/06/04
 *
 * @version 1.0
 *
 * Writes to a shared memory.
 *
 */
#include "shmem.h"


int main(int argc, char *argv[])
{

    int shared_memory_key = -1;
    int buf = -1;
    static int sem_r = -1;
    static int sem_w = -1;
    static int size = -1;
    static int cnt =  -1;
    int* shared_memory = NULL;

    errno = 0;

    /* check command line arguments */
    if ((size = check_arguments(argc, argv)) == ERROR)
    {
        print_usage();
        return ERROR;
    }
    /* get both semaphores */
    if((sem_r = get_semid(SEMKEY_R, 0))==-1)
    {
        clean_up(sem_w, &shared_memory, shared_memory_key, ERROR);
        return ERROR;
    }
    if((sem_w = get_semid(SEMKEY_W, size))==-1)
    {
        clean_up(sem_w, &shared_memory, shared_memory_key, ERROR);
        return ERROR;
    }
    /* initialize shared memory */
    if((shared_memory_key =  get_shmem(SHMEMKEY,size))==-1)
    {
        clean_up(sem_w, &shared_memory, shared_memory_key, ERROR);
        return ERROR;
    }
    /* attach memory to process */
    attach_shmem(shared_memory_key,&shared_memory, SEMKEY_W);
    if(shared_memory == NULL)
    {
        clean_up(sem_w, &shared_memory, shared_memory_key, ERROR);
        return ERROR;
    }

    /* start the writer */
    do
      {
        if(P(sem_w)==-1)
        {
            if(errno == EINTR)
            {
                /*EINTR sagt uns, dass ein Interrupt vorliegt. */
                errno = 0;
                continue;
            }
            else
            {
                clean_up(sem_w, &shared_memory, shared_memory_key, ERROR);
                fprintf(stderr, "Error bei P, writer. %s", strerror(errno));
                return ERROR;
            }
        }
        buf=fgetc(stdin);
        cnt++;
        cnt = cnt%size;
        *(shared_memory+cnt) = buf;




        if(V(sem_r)==-1)
        {
            if(errno == EINTR)
            {
                /*EINTR sagt uns, dass ein Interrupt vorliegt. */
                errno = 0;
                continue;
            }
            else
            {
                clean_up(sem_w, &shared_memory, shared_memory_key, ERROR);
                fprintf(stderr, "Error bei P, writer. %s", strerror(errno));
                return ERROR;
            }
        }
    }
    while(buf != EOF );

    /* error handling for fgetc() */
    if (ferror(stdin)) {
        clean_up(sem_w, &shared_memory, shared_memory_key, ERROR);
        fprintf(stderr, "Error stdin! %s", strerror(errno));
		return ERROR;
	}

    detach_shmem(shared_memory_key,SEMKEY_W);

    return 0;
}





